<template>
  <view class="custom-header" :style="grouptitleStyle">
    <image
      :lazy-load="true"
      class="custom-header__back"
      :src="RETURN_ARROWS"
      @tap="handleBackBtn"
    />
    <text class="custom-header-title">{{ title }}</text>
    <text></text>
  </view>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import Taro from "@tarojs/taro";
import { RETURN_ARROWS } from "@/config/component-config/clock-header";
import { SCORLL_TOP_OFFSET } from "@/config/base-common";
const OFFSET = 10; // 距离顶部便宜量
const GASBAG_TITLE_OFFSET = 20; // 顶部气囊按钮向下偏移量 总共标题的高 = 气囊的高度 + 距离顶部的位置 + 此偏移量

@Component({})
export default class CustomHeader extends Vue {
  /* 气泡按钮高度 */
  gasbagHeight: number = 0;
  /* 气泡按钮距离顶部的高度 */
  gasbagMarTop: number = 0;
  /* header返回按钮 */
  RETURN_ARROWS: string = RETURN_ARROWS;

  /* 标题 */
  @Prop({ default: "习惯百日行" }) readonly title: string;
  /* 距离顶部高度 */
  @Prop({ default: 0 }) readonly scrollTop: number;
  /* 顶部背景色或背景图 */
  @Prop({ default: "#ffffff" }) readonly bgColor: string;
  /* 顶部返回事件 */
  @Prop({ default: false }) readonly isCustomBack: boolean;
  /* 离开前置事件 */
  @Prop({ default: () => {} }) readonly beforeLeaveFn: Function;
  /* 离开禁止事件 */
  @Prop({ default: false }) readonly disabled: boolean;

  created() {
    const { height, top } = Taro.getMenuButtonBoundingClientRect();
    this.gasbagHeight = height;
    this.gasbagMarTop = top;
  }
  /* 设置自定义header的样式 */
  get grouptitleStyle() {
    let backgroundColor = {};
    if (this.scrollTop) {
      // let isBgUrl = this.bgColor.startsWith('#')
      backgroundColor = {
        "background-color":
          this.scrollTop > SCORLL_TOP_OFFSET ? this.bgColor : "unset"
      };
    }
    return {
      height: `calc(${this.gasbagHeight +
        this.gasbagMarTop}px + ${GASBAG_TITLE_OFFSET}rpx)`,
      "line-height": `${this.gasbagHeight}px`,
      "padding-top": `${this.gasbagMarTop}px`,
      ...backgroundColor
    };
  }
  handleBackBtn(e) {
    e.stopPropagation();
    /**禁止离开 */
    if (this.disabled) return;
    if (this.isCustomBack) return this.$emit("back");
    const pages = Taro.getCurrentPages();
    Taro.getStorageSync("comeFromToday") && Taro.setStorageSync("today", 1);
    /**离开前置事件 */
    this.beforeLeaveFn && this.beforeLeaveFn();
    if (pages.length < 2) {
      Taro.switchTab({
        url: "/pages/index/index"
      });
      return;
    }
    Taro.navigateBack({
      delta: 1
    });
  }
}
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
.custom-header {
  font-size: 37px;
  width: 100%;
  font-weight: bold;
  text-align: center;
  position: sticky;
  top: 0;
  z-index: 11;
  transition: background-color 0.5s;
  &__back {
    width: 40px;
    height: 40px;
    position: absolute;
    left: 24px;
    bottom: 30px;
  }
  &-title {
    display: inline-block;
    max-width: 38%;
    @include textEllipsis;
  }
}
</style>
